package com.bawei.hgshop.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import com.bawei.hgshop.entity.Cart;
import com.bawei.hgshop.entity.OrderDetail; 
import com.bawei.hgshop.entity.Orders;
import com.bawei.hgshop.entity.User;
import com.bawei.hgshop.mapper.CartMapper;
import com.bawei.hgshop.mapper.OrderMapper;
import com.bawei.hgshop.mapper.UserMapper;
import com.bawei.hgshop.service.UserService;

@Service
public class UserServiceImpl  implements UserService{
	
	// 用户
	@Autowired
	UserMapper userMapper;
	
	// 购物车
	@Autowired
	CartMapper cartMapper;
	
	@Autowired
	OrderMapper orderMapper;

	@Override
	public int register(User user) {
		// TODO Auto-generated method stub
		//保存到数据库当中
		return userMapper.insert(user);
	}

	/**
	 * 登录
	 */
	@Override
	public User login(User user) {
		// TODO Auto-generated method stub
		User loginUser = userMapper.findUserBypwd(user);
		
		return loginUser;
	}

	@Override
	public List<Cart> listCart(int uid) {
		// TODO Auto-generated method stub
		return cartMapper.listCart(uid);
	}

	@Override
	public void addCart(Cart cart) {
		// TODO Auto-generated method stub
		cartMapper.add(cart);
		
	}

	@Override
	public void createOrder(int uid,  int[] cartIds) {
		// TODO Auto-generated method stub
		
		//0  先去购物车当中查询数据 为了得到skuid， 购买数量 单价 
		List<Cart>  cartList = cartMapper.listCartByIds(uid,cartIds);
		
		// 计算整个订单的总价格
		BigDecimal orderSumTotal = new BigDecimal(0.0);
		
		for (Cart cart : cartList) {
			orderSumTotal=orderSumTotal.add(cart.getSumTotal()); // 相当于简单类型中  + 
		}
		//1、 先添加订单主表  需要计算总价格
		Orders orders = new Orders();
		orders.setUid(uid);
		orders.setCreateTime(new Date());
		orders.setSumtotal(orderSumTotal);// 设置总价格
		orders.setAddress("配送地址");
		orderMapper.add(orders);// 添加到数据库
			
		//2、 添加订单明细表
		for (Cart cart : cartList) {
			OrderDetail orderDetail = new OrderDetail();
			orderDetail.setOid(orders.getOid());//设置外键 也就是订单主表id
			orderDetail.setSku(cart.getSku());//设置sku
			orderDetail.setPnum(cart.getPnum());// 购买数量
			orderDetail.setTotal(cart.getSumTotal());// 总价格
			// 添加到数据库
			orderMapper.addDetail(orderDetail);
		}
		//3 删除购物车中表数据  批量删除也可以
		for (Cart cart : cartList) {
			cartMapper.delById(cart.getId());
		}
		
		// 4、减少库存  企业里这里可能要使用kfka 消息
		for (Cart cart : cartList) {
			
			orderMapper.decreaseStock(cart.getSku().getId(),cart.getPnum());
		}
		
		
	}

}
